package menu

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	"sg-backend/global"
	"sg-backend/logger"
	"sg-backend/model/user"
	"sg-backend/utils"
)

/*
 * 3
 * PUT,修改菜单请求，/api/user/menu
 */

func UpdateMenu(ctx *fiber.Ctx) error {
	// 权限验证
	utils.CheckPermsByTag("UserMenu", global.AuthUser.UserId, "update")

	var putForm _MenuDto
	if err := ctx.BodyParser(&putForm); err != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": fmt.Sprintf("数据解释出错！%s", err),
		})
	}

	// 数据获取完成
	// 获取数据成功，开始验证
	var menus []user.Menu

	// 1，同层级下菜单不能重名
	noDuplicateCheck := global.DB.Not(
		"id = ?", putForm.Id,
	).Where(
		"title = ? AND pid = ?", putForm.Title, putForm.Pid,
	).Find(&menus)
	if noDuplicateCheck.RowsAffected != 0 {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "同层级菜单不允许重名！",
		})
	}

	// 2，权限标志要唯一，排除自身，避免维修改时无法提交
	privilegeTagCheck := global.DB.Not(
		"id = ?", putForm.Id,
	).Where(
		"privilege_name = ?", putForm.PrivilegeName,
	).Find(&menus)
	if privilegeTagCheck.RowsAffected != 0 {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "权限标识需要全局唯一！",
		})
	}

	// 验证完成，开始保存修改
	var menuObj = user.Menu{Id: putForm.Id}
	global.DB.First(&menuObj)
	menuObj.Title = putForm.Title
	menuObj.Url = putForm.Url
	menuObj.Show = putForm.Show
	menuObj.OrderNum = putForm.OrderNum
	menuObj.PrivilegeName = putForm.PrivilegeName
	r := global.DB.Save(&menuObj)
	if r.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": fmt.Sprintf("修改保存到数据库出错！记录：%+v", r.Error),
		})
	}

	// 写日志
	logger.DbInfo(global.AuthUser.Username, fmt.Sprintf("菜单修改成功！菜单：%+v", putForm))
	return ctx.JSON(fiber.Map{
		"status":  "done",
		"message": "修改成功！",
	})
}
